package com.yun.algorithm.backtracking.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Leetcode47_Permute {
    public List<List<Integer>> permute(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        dfs(nums, new boolean[nums.length], new LinkedList<>(), result);
        return result;
    }

    private void dfs(int[] nums, boolean[] visited, LinkedList<Integer> stack, List<List<Integer>> result) {
        if (stack.size() == nums.length) {
            //System.out.println(stack);
            result.add(new ArrayList<>(stack));
            return;
        }
        //遍历nums数组,发现没有被使用的数字,则将其标记为使用,并加入stack
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {//找出重复数字
                continue;
            }
            //[false,false,false]()
            if (!visited[i]) {
                stack.push(nums[i]);//(1)
                visited[i] = true;//[true,false,false]
                dfs(nums, visited, stack, result);
                visited[i] = false;//[false,false,false]
                stack.pop();//()
            }
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> permute = new Leetcode47_Permute().permute(new int[]{1, 1, 1, 3});
        for (List<Integer> s : permute) {
            System.out.println(s);
        }
    }
}
